#include <dbg.h>

#include <cassert>

using namespace std;

class Solution {
public:
    int maxSubarrayLength(vector<int>& nums, int k) {
        int res = 0;
        int left = 0;
        unordered_map<int, int> cnt;
        for (int right = 0; right < nums.size(); ++right) {
            ++cnt[nums[right]];
            while (cnt[nums[right]] > k) {
                --cnt[nums[left]];
                ++left;
            }
            res = max(res, right - left + 1);
        }
        return res;
    }
};

int main() {
    Solution s;

    vector<int> nums1 = {1, 2, 3, 1, 2, 3, 1, 2};
    vector<int> nums2 = {1, 2, 1, 2, 1, 2, 1, 2};
    vector<int> nums3 = {5, 5, 5, 5, 5, 5, 5};

    int k1 = 2;
    int k2 = 1;
    int k3 = 4;

    assert(s.maxSubarrayLength(nums1, k1) == 6);
    assert(s.maxSubarrayLength(nums2, k2) == 2);
    assert(s.maxSubarrayLength(nums3, k3) == 4);

    return 0;
}